# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html


# useful for handling different item types with a single interface
from itemadapter import ItemAdapter
import os


class DragonrajaPipeline:
    def open_spider(self, spider):
        print('开始下载龙族全篇')

    def process_item(self, item, spider):
        if not os.path.exists(f"./龙族全篇/{item['charpter']}"):
            os.makedirs(f"./龙族全篇/{item['charpter']}")
        print(item['title'])
        fp = open(
            f"./龙族全篇/{item['charpter']}/{item['title']}.txt",
            'at',
            encoding='utf-8')
        fp.write(item['content'])
        fp.close()
        return item

    def close_spider(self, spider):
        print('下载完毕')
